<?php

use Illuminate\Http\Request;
use App\Tables\User;
use Illuminate\Validation\Rule;
use App\Rules\MobileRule;

/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/

Route::get('/user', function (Request $request) {
    return response()->json(ajax_return(true, 'ok', $request->user('api-admin')));
})->middleware(['auth:api-admin', 'scope:user-info', 'auth.status:api']);

/**
 * 后台修改个人信息
 */
Route::patch('/user/profiles', function (Request $request) {
    $rules = [];
    $user = User::find($request->user('api-admin')->id);
    if ($request->filled('realname')) {
        $user->realname = $request->realname;
        $rules['realname'] = [ 'required', 'string', 'min:2', 'max:8' ];
    }

    if ($request->filled('nickname')) {
        $user->nickname = $request->nickname;
        $rules['nickname'] = [ 'required', 'string', 'min:2', 'max:8' ];
    }

    if ($request->filled('email')) {
        $user->email = $request->email;
        $rules['email'] = [
            'email',
            Rule::unique('users')->ignore($user->id)
        ];
    }

    if ($request->filled('mobile')) {
        $user->mobile = $request->mobile;
        $rules['mobile'] = [
            new MobileRule(),
            Rule::unique('users')->ignore($user->id)
        ];
    }

    if ($request->filled('sex')) {
        $user->sex = $request->sex;
        $rules['sex'] = 'required|in:0,1,2';
    }

    Validator::make($request->all(), $rules)->validate();

    if ($user->save()) {
        return response()->json(ajax_return(true, '修改个人信息成功', new \App\Http\Resources\UserResource($user)));
    }

    return response()->json(ajax_return(false, '修改个人信息失败'));

})->middleware(['auth:api-admin', 'auth.status:api'])->name('user.profiles.update');

/**
 * 修改密码
 */
Route::patch('/user/password/reset', function (Request $request) {
    $rules = [];
    $user = User::find($request->user('api-admin')->id);

    // 验证用户密码
    $rules['old_password'] = new \App\Rules\checkOldPasswordRule('users', 'password', $user->id);
    $rules['password'] = "required|string|max:18|min:6";
    $rules['re_password'] = 'same:password';

    Validator::make($request->all(), $rules)->validate();

    $user->password = bcrypt($request->password);
    if ($user->save()) {
        return response()->json(ajax_return(true, '密码修改成功', new \App\Http\Resources\UserResource($user)));
    }

    return response()->json(ajax_return(false, '密码修改失败'));

})->middleware(['auth:api-admin', 'auth.status:api'])->name('user.password.reset');
/**
 * 后台用户
 */
Route::get('/admins', 'AdminController@index')
    ->middleware(['auth:api-admin', 'auth.status:api', 'role:system'])
    ->name('admin.user.backend.list');

Route::post('/admins', 'AdminController@add')
    ->middleware(['auth:api-admin', 'auth.status:api', 'role:system'])
    ->name('admin.user.backend.create');

Route::patch('/admins/{id}', 'AdminController@update')
    ->middleware(['auth:api-admin', 'auth.status:api', 'role:system'])
    ->name('admin.user.backend.update');

Route::patch('/admins/{id}/status/{status}', 'AdminController@toggleStatus')
    ->middleware(['auth:api-admin', 'auth.status:api', 'role:system'])
    ->name('admin.user.backend.status.update');

Route::patch('/admins/roles/{user_id}/{role_ids}', 'AdminController@roleAttach')
    ->middleware(['auth:api-admin', 'auth.status:api', 'role:system'])
    ->name('admin.user.backend.roles.attach');
/**
 * 普通用户
 */
Route::get('/users', 'UserController@index')
    ->middleware(['auth:api-admin', 'auth.status:api', 'role:system|admin'])
    ->name('admin.user.general.list');

Route::post('/users', 'UserController@add')
    ->middleware(['auth:api-admin', 'auth.status:api', 'role:system|admin'])
    ->name('admin.user.general.create');

Route::patch('/users/{id}', 'UserController@update')
    ->middleware(['auth:api-admin', 'auth.status:api', 'role:system|admin'])
    ->name('admin.user.general.update');

Route::patch('/users/{id}/status/{status}', 'UserController@toggleStatus')
    ->middleware(['auth:api-admin', 'auth.status:api', 'role:system|admin'])
    ->name('admin.user.general.status.update');

Route::post('/users/{id}/backend/charge/{money}', 'UserController@backendCharge')
    ->middleware(['auth:api-admin', 'auth.status:api', 'role:system|admin'])
    ->name('admin.user.general.backend.charge');

Route::post('/users/batch/give/score', 'UserController@batchGiveScore')
    ->middleware(['auth:api-admin', 'auth.status:api', 'role:system|admin'])
    ->name('admin.user.general.batch.give.score');

Route::post('/users/give/score', 'UserController@giveScore')
    ->middleware(['auth:api-admin', 'auth.status:api', 'role:system|admin'])
    ->name('admin.user.general.give.score');

/**
 * 代理商管理
 */
Route::get('/agents', 'AgentController@index')
    ->middleware(['auth:api-admin', 'auth.status:api', 'role:system|admin|agent'])
    ->name('admin.user.agents.list');

Route::post('/agents', 'AgentController@add')
    ->middleware(['auth:api-admin', 'auth.status:api', 'role:system|admin|agent'])
    ->name('admin.user.agents.create');

Route::patch('/agents/{id}', 'AgentController@update')
    ->middleware(['auth:api-admin', 'auth.status:api', 'role:system|admin|agent'])
    ->name('admin.user.agents.update');

Route::patch('/agents/{id}/status/{status}', 'AgentController@toggleStatus')
    ->middleware(['auth:api-admin', 'auth.status:api', 'role:system|admin|agent'])
    ->name('admin.user.agents.status.update');

Route::patch('agents/{id}/pass', 'AgentController@pass')
    ->middleware(['auth:api-admin', 'auth.status:api', 'role:system|admin'])
    ->name('admin.user.agent.audit.pass');

Route::patch('agents/{id}/reject', 'AgentController@reject')
    ->middleware(['auth:api-admin', 'auth.status:api', 'role:system|admin'])
    ->name('admin.user.agent.audit.rejection');


Route::get('/agents/names', 'AgentController@names')->name('agent.names');

/**
 * 设备管理
 */
Route::get('devices', 'DeviceController@index')
    ->middleware(['auth:api-admin', 'auth.status:api', 'role:system|admin|agent'])
    ->name('admin.device.list');

Route::post('devices', 'DeviceController@create')
    ->middleware(['auth:api-admin', 'auth.status:api', 'role:agent'])
    ->name('admin.device.add');

Route::post('devices/batch/{number}', 'DeviceController@batchCreate')
    ->middleware(['auth:api-admin', 'auth.status:api', 'role:agent'])
    ->name('admin.device.batch.add');

Route::get('devices/{id}', 'DeviceController@detail')
    ->middleware(['auth:api-admin', 'auth.status:api'])
    ->name('admin.device.detail');

Route::put('devices/{id}', 'DeviceController@update')
    ->middleware(['auth:api-admin', 'auth.status:api', 'role:agent'])
    ->name('admin.device.edit');

Route::patch('devices/batch/ladder_price/{agent_user_id}', 'DeviceController@batchUpdateLadderPrice')
    ->middleware(['auth:api-admin', 'auth.status:api', 'role:admin|system'])
    ->name('admin.device.edit');
/**
 * 订单管理
 */
Route::get('orders', 'OrderController@index')
    ->middleware(['auth:api-admin', 'auth.status:api', 'role:system|admin|agent'])
    ->name('admin.order.list');

/**
 * 系统参数设置
 */
Route::get('/configs/system', 'ConfigController@getSystem')
    ->middleware(['auth:api-admin', 'auth.status:api'])
    ->name('admin.config.system.get');

Route::post('/configs/system', 'ConfigController@setSystem')
    ->middleware(['auth:api-admin', 'auth.status:api', 'role:system|admin'])
    ->name('admin.config.system.set');

/**
 * 角色权限管理
 */
Route::get('/roles', 'RoleController@index')
    ->middleware(['auth:api-admin', 'auth.status:api', 'role:system|admin'])
    ->name('admin.role.list');

/**
 * 类目管理
 */
Route::get('/categories/{parent_id}', 'CategoryController@categories')
    ->middleware(['auth:api-admin', 'auth.status:api'])
    ->name('admin.categories.list');

Route::post('/categories', 'CategoryController@add')
    ->middleware(['auth:api-admin', 'auth.status:api'])
    ->name('admin.categories.create');

Route::put('/categories/{id}', 'CategoryController@update')
    ->middleware(['auth:api-admin', 'auth.status:api'])
    ->name('admin.categories.update');

Route::patch('/categories/{id}/status/{status}', 'CategoryController@toggleStatus')
    ->middleware(['auth:api-admin', 'auth.status:api'])
    ->name('admin.categories.status.update');

Route::get('/categories/{id}/selected/parents', 'CategoryController@selectedParents')
    ->middleware(['auth:api-admin', 'auth.status:api'])
    ->name('admin.categories.selected.parents');

Route::get('/categories/format/code/{name}', 'CategoryController@formatCode')
    ->middleware(['auth:api-admin', 'auth.status:api'])
    ->name('admin.categories.format.code');

/**
 * 报表统计
 */
Route::get('/reports/agent/income/month', 'ReportController@agentIncomeForMonth')
    ->middleware(['auth:api-admin', 'auth.status:api'])
    ->name('admin.report.agent.income.month');

Route::get('/reports/user/balance/month', 'ReportController@userBalanceForMonth')
    ->middleware(['auth:api-admin', 'auth.status:api'])
    ->name('admin.report.user.balance.month');

Route::get('/reports/user/balance/record', 'ReportController@userBalanceRecord')
    ->middleware(['auth:api-admin', 'auth.status:api'])
    ->name('admin.report.user.balance.record');

Route::get('/reports/user/score/record', 'ReportController@userScoreRecord')
    ->middleware(['auth:api-admin', 'auth.status:api'])
    ->name('admin.report.user.score.record');

Route::get('/reports/agent/balance/record', 'ReportController@agentBalanceRecord')
    ->middleware(['auth:api-admin', 'auth.status:api'])
    ->name('admin.report.agent.balance.record');

Route::get('/reports/agent/score/record', 'ReportController@agentScoreRecord')
    ->middleware(['auth:api-admin', 'auth.status:api'])
    ->name('admin.report.agent.score.record');

/**
 * 系统操作日志
 */
Route::get('/operation/logs', 'OperationLogController@index')
    ->middleware(['auth:api-admin', 'auth.status:api', 'role:admin|system'])
    ->name('admin.operation.logs');

/**
 * 消息管理
 */
Route::get('/messages/sms/list', 'MessageController@smsList')
    ->middleware(['auth:api-admin', 'auth.status:api', 'role:admin|system'])
    ->name('admin.message.sms.list');

/**
 * Cms模块
 */
Route::group([
    'prefix' => 'cms',
    'middleware' => ['auth:api-admin', 'auth.status:api']
], function () {
    /**
     * 文章管理
     */
    Route::get('articles', 'ArticleController@index')->name('admin.cms.article.list');
    Route::post('articles', 'ArticleController@store')->name('admin.cms.article.create');
    Route::get('articles/{id}', 'ArticleController@detail')->name('admin.cms.article.detail');
    Route::match(['put', 'patch'], 'articles/{id}', 'ArticleController@update')->name('admin.cms.article.update');
    Route::post('articles/upload/image', 'ArticleController@uploadImage')->name('admin.cms.article.upload.image');
    Route::delete('articles/{id}', 'ArticleController@destroy')->name('admin.cms.article.delete');
    Route::patch('articles/{id}/restore', 'ArticleController@restore')->name('admin.cms.article.restore');
    Route::patch('articles/{id}/rejection', 'ArticleController@rejection')->name('admin.cms.article.rejection');
    Route::patch('articles/{id}/pass', 'ArticleController@pass')->name('admin.cms.article.pass');

    /**
     * 标签管理
     */
    Route::get('tags', 'TagController@index')->name('admin.cms.tag.list');
    Route::post('tags', 'TagController@store')->name('admin.cms.tag.create');
    Route::match(['put', 'patch'], 'tags/{id}', 'TagController@update')->name('admin.cms.tag.update');
    Route::delete('tags/{id}', 'TagController@destroy')->name('admin.cms.tag.delete');

});